<?php

namespace app\index\controller;

use app\BaseController;

class Download extends BaseController
{
    // 下载文件php方式，非直连
    public function downFile()
    {
        $file_path = 'storage/myzipfile.zip';
        // $file_path = 'storage/1.txt';
        if (file_exists($file_path)) {
            $size = filesize($file_path);
            $start = 0;
            $end = $size - 1;

            if (isset($_SERVER['HTTP_RANGE'])) {
                if (preg_match('/bytes=h*(d+)-(d*)[D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
                    $start = intval($matches[1]);
                    if (!empty($matches[2])) {
                        $end = intval($matches[2]);
                    }
                }
            }
            if ($start > $end || $end > $size - 1 || $start < 0) {
                header('HTTP/1.1 416 Requested Range Not Satisfiable');
                header("Content-Range: bytes $start-$end/$size");
                exit;
            }
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . basename($file_path));
            header('Content-Transfer-Encoding: binary');
            header("Content-Range: bytes $start-$end/$size");
            header('Accept-Ranges: bytes');
            header('Content-Length: ' . ($end - $start + 1));
            header("Cache-control: private");
            header('Pragma: private');
            header('Expires: ' . gmdate('D, d M Y H:i:s T', time() + 3600));

            $fp = fopen($file_path, 'rb');
            fseek($fp, $start);
            $buffer_size = 1024 * 8; //每次读取8 KB
            $bytes_send = 0;
            while (!feof($fp) && ($bytes_send < $end - $start + 1)) {
                $buffer = fread($fp, $buffer_size);
                echo $buffer;
                flush();
                $bytes_send += strlen($buffer);
            }
            fclose($fp);
            exit;
        } else {
            die('File not found.');
        }
    }
}
